import cv2 as cv
import numpy as np
import sys
from matplotlib import pyplot as plt


# 回调函数，用于处理滑动条值的变化
def on_intensity_change1(val):
    global gray, intensity
    intensity = val
    _, gray_B = cv.threshold(image, intensity, 255, cv.THRESH_BINARY)
    # 形态学运算：
    gray_B = openClose(gray_B)
    cv.imshow('gray_B', gray_B)


# 回调函数，用于处理直方图均衡化后滑动条值的变化
def on_intensity_change2(val):
    global gray, intensity
    intensity = val
    _, gray_B2 = cv.threshold(image_result, intensity, 255, cv.THRESH_BINARY)
    # 形态学运算：
    gray_B2 = openClose(gray_B2)
    cv.imshow('gray_B2', gray_B2)

def openClose(img):
    # 生成5*5矩形结构元素

    Close_kernel_keys = cv.getStructuringElement(0, (6, 6))
    Open_kernel_keys = cv.getStructuringElement(0, (2, 2))
    # 形态学运算：先闭后开（闭运算填充缝隙，开运算去除毛刺噪声）

    close_img = cv.morphologyEx(img, cv.MORPH_CLOSE, Close_kernel_keys)  # 闭运算：先膨胀再腐蚀
    open_img = cv.morphologyEx(close_img, cv.MORPH_OPEN, Open_kernel_keys)

    return open_img

if __name__ == '__main__':
    # # 读取图像并判断是否读取成功
    # img = cv.imread(r"E:\studylife\detectflaws\code\imgEnhance\img.jpg")
    # # 调整图像大小
    # img = cv.resize(img, (640, 480))
    # if img is None:
    #     print('Failed to read img.jpg.')
    #     sys.exit()

    # 读取图像
    image = cv.imread(
        r"E:\studylife\detectflaws\code\findFlaws\1.jpg", 0)
    # 判断图片是否读取成功
    if image is None:
        print('Failed to read equalizeHist.jpg.')
        sys.exit()

    # 一 绘制原图直方图
    plt.hist(image.ravel(), 256, [0, 256])
    plt.title('Origin Image')
    # plt.show()
    # 进行均衡化并绘制直方图
    # image_result = cv.equalizeHist(image)  # 普通直方图均衡化
    # 自适应直方图均衡化
    clahe = cv.createCLAHE(clipLimit=20, tileGridSize=(2, 2))  # clipLimit：这是对比度限制的阈值
    image_result = clahe.apply(image)  # tileGridSize：将输入图像划分为M × N块，然后对每个局部块应用直方图均衡化

    image = cv.resize(image, (640, 480))
    image_result = cv.resize(image_result, (640, 480))

    plt.hist(image_result.ravel(), 256, [0, 256])
    plt.title('Equalized Image')
    # plt.show()
    # 展示均衡化前后的图片
    cv.imshow('Origin Image', image)
    cv.imshow('Equalized Image', image_result)
    cv.waitKey(0)

    # 二 对image和image_result做滤波处理
    #image = cv.GaussianBlur(image, (5, 5), 10, 20)
    image = cv.medianBlur(image, 3)

    image_result = cv.GaussianBlur(image_result, (5, 5), 10, 20)
    image_result = cv.medianBlur(image_result, 3)

    cv.imshow('Origin Image2', image)
    cv.imshow('Equalized Image2', image_result)
    cv.waitKey(0)

    # 三 使用滑块阈值调节原相位图(形态学处理后）
    # gray = cv.cvtColor(image_result, cv.COLOR_BGR2GRAY)
    intensity = int(np.mean(image))  # 使用平均灰度值作为初始阈值强度

    cv.namedWindow('gray_B')
    cv.createTrackbar('intensity', 'gray_B', intensity, 255, on_intensity_change1)

    # 初始展示二值化图像
    _, gray_B = cv.threshold(image, intensity, 255, cv.THRESH_BINARY)

    # 形态学运算：
    gray_B = openClose(gray_B)
    cv.imshow('gray_B', gray_B)

    # 四 使用滑块阈值调节直方图均衡化后相位图(形态学处理后）
    # gray = cv.cvtColor(image_result, cv.COLOR_BGR2GRAY)
    intensity2 = int(np.mean(image_result))  # 使用平均灰度值作为初始阈值强度

    cv.namedWindow('gray_B2')
    cv.createTrackbar('intensity2', 'gray_B2', intensity2, 255, on_intensity_change2)

    # 初始展示二值化图像
    _, gray_B2 = cv.threshold(image_result, intensity, 255, cv.THRESH_BINARY)
    # 形态学运算：
    gray_B2 = openClose(gray_B2)
    cv.imshow('gray_B2', gray_B2)

    cv.waitKey(0)
    cv.destroyAllWindows()
